<?php
/**
 * Created by PhpStorm.
 * User: GUO
 * Date: 2017/8/22
 * Time: 14:19
 */
require_once 'WechatReceive.php';
require_once 'WechatOauth.php';
require_once 'WechatMenu.php';
require_once 'WechatUser.php';
require_once 'WechatMessageCache.php';
class Wechat{
    /**
     * @var string|WechatReceive
     * 这里作为微信公众号的消息入口（包括绑定入口）。用户在公众号发送的消息，微信服务器会推送到这里（index）.这个类可迁到开发的请求控制器中
     */
    private $WechatReceive = '';//消息实例
    private $WechatOauth = '';//授权实例
    private $WechatMenu = '';//菜单实例
    private $WechatUser = '';//用户实例
    private $FromUserName = '';//消息发送者
    private $ToUserName = '';  //消息接受者
    private $MsgType = '';  //接收消息的类型
    private $CreateTime = '';  //接收消息的时间
    private $Keyword = '';  //接收消息的值

    public function __construct()
    {
        //parent::__construct();
        /*$this->load->library('Wechat/WechatReceive');
        $this->load->library('Wechat/WechatOauth');*/
        $this->WechatReceive = new WechatReceive();
        $this->WechatOauth = new WechatOauth();
        $this->WechatMenu = new WechatMenu();
        $this->WechatUser = new WechatUser();
    }

    public function index()
    {
        if (isset($_GET["echostr"])) exit($_GET["echostr"]);

        $postObj = $this->WechatReceive->getRev();//获取微信服务器发来的内容
        $wxData = $this->WechatReceive->getRevData();
        $this->FromUserName = $this->WechatReceive->getRevFrom();//消息发送者
        $this->ToUserName = $this->WechatReceive->getRevTo();//消息接受者
        $this->CreateTime = $this->WechatReceive->getRevCtime();//接收消息的时间
        $this->MsgType = $this->WechatReceive->getRevType();//接收消息的类型

        $this->Keyword = trim($this->WechatReceive->getRevContent());//接收消息的值
        write_file('./application/logs/test.txt', date('Y-m-d H:i:s') . json_encode($wxData) . "/n", 'a+');

        //消息排重
        $msgCache = WechatMessageCache::getInstance();
        if(in_array($wxData['MsgID'],$msgCache::$list) || in_array($wxData['FromUserName'] . $wxData['CreateTime'],$msgCache::$list)){
            write_file('./application/logs/test.txt', date('Y-m-d H:i:s') . '进来了', 'a+');
            exit('');
        }

        $msgCache::$list[] = $wxData['MsgID'];
        $msgCache::$list[] = $wxData['FromUserName'] . $wxData['CreateTime'];
        //write_file('./application/logs/test.txt', date('Y-m-d H:i:s') . json_encode($msgCache::$list) . "/n", 'a+');
        /*
        * 1、click：点击推事件
        * 用户点击click类型按钮后，微信服务器会通过消息接口推送消息类型为event的结构给开发者（参考消息接口指南）
        * 并且带上按钮中开发者填写的key值，开发者可以通过自定义的key值与用户进行交互；
        */

        if ($this->MsgType == 'event' && $wxData['Event'] == 'CLICK') {
            $this->Keyword = trim($this->WechatReceive->getRevEvent()['key']);//接收消息的值
        }

        //2, 关注事件
        if ($this->MsgType == 'event' && $wxData['Event'] == 'subscribe') {
            $this->WechatReceive->sendText('欢迎来到超大大的测试公众号', $this->FromUserName, $this->ToUserName);
        }

        if ($this->MsgType == 'event' && $wxData['Event'] == 'TEMPLATESENDJOBFINISH' && $wxData['Status'] == 'success') {
            write_file('./application/logs/test.txt', date('Y-m-d H:i:s') . '进来了');
            //exit('');
        }


        

        //回复文本消息
        if ($this->Keyword == '文本') {
            $this->WechatReceive->sendText('文本回复', $this->FromUserName, $this->ToUserName);
        }

        //回复图文消息
        $wx_img = array(
            'title'=>'你好',
            'desc'=>'123445',
            'pic'=>'https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=4135213963,1816457489&fm=58',
            'url' => 'https://www.baidu.com/'
        );
        if ($this->Keyword == '图文') {
            $this->WechatReceive->sendImg($this->FromUserName, $this->ToUserName, $wx_img['title'], $wx_img['desc'], $wx_img['pic'], $wx_img['url']);
        }

        //图片消息
        if ($this->Keyword == '图片') {
            $this->WechatReceive->sendPic('SzANT95HE3xfOsQeyi4LhdSTs1YEKMNkDCydBO9RiZOZMIrZ5KRLu0wQetmMY82c');
        }


        //多图文消息
        if ($this->Keyword == '多图文') {
            $content = array();
            $content[] = array("title"=>"多图文1标题", "description"=>"", "picUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "url" =>"http://m.cnblogs.com/?u=txw1958");
            $content[] = array("title"=>"多图文2标题", "description"=>"", "picUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "url" =>"http://m.cnblogs.com/?u=txw1958");
            $content[] = array("title"=>"多图文3标题", "description"=>"", "picUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "url" =>"http://m.cnblogs.com/?u=txw1958");
            $this->WechatReceive->sendImgs($content);
        }


        //语音消息
        if ($this->Keyword == '语音') {
            $this->WechatReceive->sendVoice('1j6ZoR3_4PqFbYu7jrZgV9dWQlIUUTfvvRZjxIjdp4Iy_vrrSXHZNLn9HIQyty86','amr');
        }


        //群发消息
        if ($this->Keyword == '群发111') {
            $data = [
                'touser' => [
                    'om-6EwW9cpnlWHxHkJ-n9rSdSV6c',
                    'om-6EweGFUy3BtiWyMYURuKzLlOY'
                ],
                "msgtype"=>"text",
                "text"=> ["content" => "hello"]
            ];
            $res = $this->WechatReceive->sendMassMessage($data);
            write_file('./application/logs/test.txt', date('Y-m-d H:i:s') . json_encode($res));die;
        }


        //匹配其他输入
        if ($this->Keyword == '123456789') {
            $this->WechatReceive->sendText('晴转多云', $this->FromUserName, $this->ToUserName);
        }

        //发送客服消息（文本）
        if ($this->Keyword == 'ggg') {
            $data = array(
                'touser' => $this->FromUserName,
                'msgtype' => 'text',
                'text' => array('content' => 'hhh')
            );
            $result = $this->WechatReceive->sendCustomMessage($data);
        }
        //发送模板消息
        if ($this->Keyword == '模板') {
            $data = array(
                'touser' => 'om-6EwW9cpnlWHxHkJ-n9rSdSV6c',
                'template_id' => '1UsrT-x0ATE1RHSjPPWbwYcOTdOjD1PeanMftl5drz4',
                'url' => 'http://www.baidu.com',
                'topcolor' => '#FF0000',
                'data' => []
            );
            $this->WechatReceive->sendTemplateMessage($data);
            //$this->WechatReceive->senTempBonus('', 'http://www.baidu.com', array('value' => '你的组织成功消费一笔订单', 'color' => '#173177'), '1', '2017-5-5', '到账商城余额', '2017-5-5',array('value' => '你的组织成功消费一笔订单', 'color' => '#173177'));
        }
        if ($this->Keyword == '16') {
            $this->WechatReceive->senTempOrderPay('', 'http://www.baidu.com', array('value' => '恭喜你支付成功！', 'color' => '#173177'), '1', '2015555', array('value' => '备注', 'color' => '#173177'));
        }
        if ($this->Keyword == '17') {
            $this->WechatReceive->senTempOrderStatus('', 'http://www.baidu.com', array('value' => '订单已发货！', 'color' => '#173177'), '55656165', '发货', array('value' => '备注', 'color' => '#173177'));
        }
        if ($this->Keyword == '18') {
            $this->WechatReceive->senTempRefund('', 'http://www.baidu.com', array('value' => '退款成功！', 'color' => '#173177'), '达大厦', '5.00', array('value' => '备注', 'color' => '#173177'));
        }

        //发送模板消息
        if ($this->Keyword == '20') {
            $res1  = $this->WechatReceive->setTMIndustry('10', '11');
            file_put_contents('g22.txt', json_encode($res1));

            $res = $this->WechatReceive->getTemplateList();
            file_put_contents('g11.txt', json_encode($res));
        }

        //获取openid
        if ($this->Keyword == 'snsapi_base') {
            $data = $this->WechatOauth->getUserInfo($this->Keyword);
            $this->WechatReceive->sendText($data['openid'], $this->FromUserName, $this->ToUserName);
        }

        //获取用户信息
        if ($this->Keyword == 'snsapi_userinfo') {
            $data = $this->WechatOauth->getUserInfo($this->Keyword);
            $this->WechatReceive->sendText($data['nickname'], $this->FromUserName, $this->ToUserName);
        }

        //创建菜单
        if ($this->Keyword == '创建菜单') {
            $jsonmenu = '{
                      "button":[ 
                      { 
                       "name":"用户信息", 
                       "sub_button":[ 
                       { 
                        "type":"click", 
                        "name":"编号", 
                        "key":"snsapi_base"
                       }, 
                       { 
                        "type":"click", 
                        "name":"昵称", 
                        "key":"snsapi_userinfo"
                       }, 
                       { 
                        "type":"view", 
                        "name":"本地天气", 
                        "url":"http://m.hao123.com/a/tianqi"
                       }] 
                       
                      
                      }, 
                      { 
                       "name":"瑞雪", 
                       "sub_button":[ 
                       { 
                        "type":"click", 
                        "name":"公司简介", 
                        "key":"company"
                       }, 
                       { 
                        "type":"click", 
                        "name":"趣味游戏", 
                        "key":"游戏"
                       }, 
                       { 
                        "type":"click", 
                        "name":"讲个笑话", 
                        "key":"笑话"
                       }] 
                       
                      
                      }] 
                    }';
        $res = $this->WechatMenu->createMenu($jsonmenu);

        }


        //个性化菜单
        if ($this->Keyword == '个性化菜单') {
            $jsonmenu = '{
                            "button": [{
                                    "name": "个性化菜单",
                                    "sub_button": [{
                                            "type": "click",
                                            "name": "456",
                                            "key": "123456"
                                        },
                                        {
                                            "type": "click",
                                            "name": "456789",
                                            "key": "5646789"
                                        },
                                        {
                                            "type": "view",
                                            "name": "本地天气",
                                            "url": "http://m.hao123.com/a/tianqi"
                                        }
                                    ]
                        
                        
                                },
                                {
                                    "name": "瑞雪",
                                    "sub_button": [{
                                            "type": "click",
                                            "name": "公司简介",
                                            "key": "company"
                                        },
                                        {
                                            "type": "click",
                                            "name": "趣味游戏",
                                            "key": "游戏"
                                        },
                                        {
                                            "type": "click",
                                            "name": "讲个笑话",
                                            "key": "笑话"
                                        }
                                    ]
                        
                        
                                }
                            ],
                            "matchrule": {
                                "sex": "1",
                                "country": "中国",
                                "province": "广东",
                                "city": "深圳",
                                "client_platform_type": "2",
                                "language": "zh_CN"
                            }
                        }';
            $res = $this->WechatMenu->createPersonalizedMenu($jsonmenu);

        }

    }
}